package com.nineclock.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.MessageTypeEnum;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.oss.OssClientUtils;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.*;
import com.nineclock.system.im.HxImManager;
import com.nineclock.system.mapper.*;
import com.nineclock.system.message.MessageDTO;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SysCompanyService;
import com.nineclock.system.service.SysCompanyUserService;
import com.nineclock.system.service.SysUserService;
import net.bytebuddy.asm.Advice;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysCompanyServiceImpl implements SysCompanyService {
    @Autowired
    private SysFunctionMapper functionMapper;

    @Autowired
    private SysRoleFunctionMapper roleFunctionMapper;

    @Autowired
    private SysCompanyMapper companyMapper;

    @Autowired
    private OssClientUtils ossClientUtils;

    @Autowired
    private SysCompanyUserMapper companyUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysCompanyUserRoleMapper companyUserRoleMapper;

    @Autowired
    private SysCompanyUserService companyUserService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserService userService;

    @Autowired(required = false)
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private HxImManager imManager;


    @Override
    public List<SysCompanyDTO> queryUserJoinCompany(Long userId) {
        List<SysCompany> companyList = companyMapper.queryUserJoinCompany(userId);

        if (CollectionUtils.isEmpty(companyList)) {
            throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }

        return BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);
    }

    @Override
    public SysCompanyDTO queryCompanyInfo() {

        // 从线程本地变量中获取当前登录用户信息
        Long companyId = CurrentUserHolder.get().getCompanyId();

        // 根据企业id查询企业信息
        SysCompany sysCompany = companyMapper.selectById(companyId);

        // 数据转换
        SysCompanyDTO companyDTO = BeanHelper.copyProperties(sysCompany, SysCompanyDTO.class);

        return companyDTO;
    }

    @Override
    public String uploadOSS(MultipartFile file) throws Exception {
        // 1.参数校验
        // 1.1 参数是否为空
        if (file == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 1.2 校验文件类型
        String contentType = file.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(contentType)) {
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        // 1.3 校验文件大小
        long fileSize = file.getSize();
        if (fileSize > NcConstant.maxFileSize) {
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }

        // 2.调用阿里云oss上传文件
        String url = ossClientUtils.uploadFile(file.getOriginalFilename(), file.getInputStream());

        return url;
    }

    @Override
    public void updateCompanyInfo(SysCompanyDTO companyDTO) {
        // 1.获取线程本地变量中的当前登录用户信息
        Long companyId = CurrentUserHolder.get().getCompanyId();

        // 2.更新企业信息表
        SysCompany company = new SysCompany();
        company.setId(companyId);
        company.setName(companyDTO.getName());
        company.setLogo(companyDTO.getLogo());
        companyMapper.updateById(company);

        // 3.更新员工信息表
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, companyId);

        SysCompanyUser sysCompanyUser = new SysCompanyUser();
        sysCompanyUser.setCompanyName(companyDTO.getName());
        companyUserMapper.update(sysCompanyUser, wrapper);

    }

    @Override
    public void changeSysAdmin(String code, Long userId) {
        // 参数校验
        if (StringUtils.isEmpty(code) || userId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 根据员工id查询员工信息，得到手机号码
        SysCompanyUser companyUser = companyUserMapper.selectById(userId);

        // 校验验证码是否正确
        String key = SMSConstant.SMS_CHANGE_MANAGER_KEY_PREFIX + companyUser.getMobile();
        String redisCode = (String) redisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            // 当redis验证码为空，或 验证码不一致
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        // 查询原本的主管理员信息
        SysCompanyUserDTO currentAdmin = companyUserService.getCurrentAdmin();

        // 查询当前公司的主管理员角色id
        LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
        roleWrapper.eq(SysRole::getRoleName, NcConstant.ADMIN_ROLE_SYS);
        SysRole role = roleMapper.selectOne(roleWrapper);

        // 更新员工角色关系表中的员工id
        LambdaQueryWrapper<SysCompanyUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUserRole::getCompanyUserId, currentAdmin.getId());
        wrapper.eq(SysCompanyUserRole::getRoleId, role.getId());

        SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
        companyUserRole.setCompanyUserId(userId);
        companyUserRoleMapper.update(companyUserRole, wrapper);

    }

    @Override
    public List<SysCompanyDTO> queryCompanyByName(String keyword) {
        LambdaQueryWrapper<SysCompany> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)){
            wrapper.like(SysCompany::getName, keyword);
        }
        List<SysCompany> sysCompanyList = companyMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(sysCompanyList)) {
            return BeanHelper.copyWithCollection(sysCompanyList, SysCompanyDTO.class);
        }
        return null;
    }

    @Override
    public void applyJoinCompany(SysApplyJoinCompanyUserDTO applyJoinCompanyUserDTO) {
        // 参数校验
        if (applyJoinCompanyUserDTO == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 更新用户表，用户id前端没有传
        SysUserDTO userDTO = userService.queryUser(applyJoinCompanyUserDTO.getMobile());

        SysUser sysUser = new SysUser();
        sysUser.setId(userDTO.getId());
        sysUser.setUsername(applyJoinCompanyUserDTO.getUserName());
        sysUser.setEmail(applyJoinCompanyUserDTO.getEmail());
        sysUser.setUpdateTime(new Date());
        sysUser.setLastLoginCompanyId(applyJoinCompanyUserDTO.getCompanyId());
        userMapper.updateById(sysUser);


        // 插入员工表，员工数据
        SysCompanyUser sysCompanyUser = new SysCompanyUser();
        sysCompanyUser.setUserId(userDTO.getId());
        sysCompanyUser.setCompanyId(applyJoinCompanyUserDTO.getCompanyId());
        sysCompanyUser.setCompanyName(applyJoinCompanyUserDTO.getCompanyName());
        sysCompanyUser.setPost(applyJoinCompanyUserDTO.getPost());
        sysCompanyUser.setEmail(applyJoinCompanyUserDTO.getEmail());
        sysCompanyUser.setTimeEntry(new Date());
        sysCompanyUser.setRemark(applyJoinCompanyUserDTO.getApplyReason());
        sysCompanyUser.setEnable((short) 0);
        sysCompanyUser.setCreateTime(new Date());
        sysCompanyUser.setUpdateTime(new Date());
        sysCompanyUser.setMobile(applyJoinCompanyUserDTO.getMobile());
        sysCompanyUser.setUserName(applyJoinCompanyUserDTO.getUserName());
        sysCompanyUser.setImageUrl(applyJoinCompanyUserDTO.getImageUrl());

        companyUserMapper.insert(sysCompanyUser);


        // 发送消息至MQ
        // 创建消息内容
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setMessageType(MessageTypeEnum.COMPANY_APPLY.getType()); // 消息类型（申请加入企业）
        messageDTO.setCompanyId(applyJoinCompanyUserDTO.getCompanyId().toString());
        messageDTO.setTitle(MessageTypeEnum.COMPANY_APPLY.getTitle());
        messageDTO.setContent(sysCompanyUser.getUserName() + " 申请加入企业，请及时审批"); // 内容
        messageDTO.setUseStatus(0); // 是否已读，0代表未读
        messageDTO.setAudience(MessageTypeEnum.COMPANY_APPLY.getAudience());

        // 查询企业的主管理员信息
        SysCompanyUser mainAdmin = companyUserMapper.queryMainAdminCompanyUser(
                applyJoinCompanyUserDTO.getCompanyId());

        messageDTO.setTargets(Lists.newArrayList(mainAdmin.getMobile())); // 发送的目标用户手机号码
        messageDTO.setApproveStatue(0); // 未审核
        messageDTO.setApplyUserId(userDTO.getId()); // 申请人用户id
        messageDTO.setApplyUsername(sysUser.getUsername()); // 申请人用户名
        messageDTO.setApproveUserId(mainAdmin.getUserId()); // 审批人用户id
        messageDTO.setApproveUsername(mainAdmin.getUserName()); // 审批人用户名


        // 参数1-主题:标签，参数2-消息内容
        rocketMQTemplate.convertAndSend("messagePushTopic", JSON.toJSONString(messageDTO));

        // 将用户注册到环信
        imManager.registerUser2HuanXing(sysUser);
    }

    @Override
    public void allowedJoinCompany(SysAllowedJoinCompanyUserDTO allowedJoinCompanyUserDTO) {
        if (allowedJoinCompanyUserDTO.getApproved()) { // 审核通过
            // 修改员工状态为有效
            LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysCompanyUser::getUserId, allowedJoinCompanyUserDTO.getApplyUserId());
            wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            SysCompanyUser companyUser = companyUserMapper.selectOne(wrapper);
            companyUser.setEnable((short) 1);
            companyUser.setUpdateTime(new Date());

            companyUserMapper.updateById(companyUser);

            // 推送消息至MQ，给申请用户推送通知
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setMessageType(MessageTypeEnum.COMPANY_APPLY_PASS.getType());
            messageDTO.setCompanyId(CurrentUserHolder.get().getCompanyId().toString());
            messageDTO.setTitle(MessageTypeEnum.COMPANY_APPLY_PASS.getTitle());
            messageDTO.setContent(companyUser.getUserName() + " 申请加入企业，已通过");
            messageDTO.setUseStatus(0); // 发给申请用户的，他此时未读
            messageDTO.setAudience(MessageTypeEnum.COMPANY_APPLY_PASS.getAudience());
            messageDTO.setTargets(Lists.newArrayList(companyUser.getMobile())); // 目标用户的手机号码
            messageDTO.setApproveStatue(1); // 已审核
            messageDTO.setApproveResult("1"); // 审核通过
            messageDTO.setApplyUserId(companyUser.getUserId()); // 申请人用户id
            messageDTO.setApplyUsername(companyUser.getUserName()); // 申请人用户名
            messageDTO.setApproveUserId(CurrentUserHolder.get().getId()); // 审批人用户id
            messageDTO.setApproveUsername(CurrentUserHolder.get().getUsername()); // 审批人用户名
            rocketMQTemplate.convertAndSend("messagePushTopic", JSON.toJSONString(messageDTO));

            // 推送消息至MQ，修改原本通知记录的状态
            rocketMQTemplate.convertAndSend("allowedJoinCompanyTopic", allowedJoinCompanyUserDTO.getNotifyMsgId());


        } else {
            // 删除员工信息
            LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysCompanyUser::getUserId, allowedJoinCompanyUserDTO.getApplyUserId());
            wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            companyUserMapper.delete(wrapper);
        }
    }

    @Override
    public List<SysRoleDTO> getRole(Integer page, Integer pageSize) {

        LambdaQueryWrapper<SysRole> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.likeRight(SysRole::getRoleName,NcConstant.ADMIN_ROLE_PREFIX);
        List<SysRole> sysRoles = roleMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(sysRoles)){
            List<SysRoleDTO> roleDTOS = BeanHelper.copyWithCollection(sysRoles, SysRoleDTO.class);

            List<SysRoleDTO> dtoList = roleDTOS.stream().map(sysRoleDTO -> {
                LambdaQueryWrapper<SysRoleFunction> functionWrapper = new LambdaQueryWrapper<>();
                functionWrapper.eq(SysRoleFunction::getRoleId, sysRoleDTO.getId());
                List<SysRoleFunction> sysRoleFunctions = roleFunctionMapper.selectList(functionWrapper);


                if (!CollectionUtils.isEmpty(sysRoleFunctions)) {
                    List<SysFunction> functions = sysRoleFunctions.stream().map(sysRoleFunction -> {
                        SysFunction sysFunction = functionMapper.selectById(sysRoleFunction.getFunctionId());
                        return sysFunction;
                    }).collect(Collectors.toList());

                    sysRoleDTO.setSysFunctionAbbrList(BeanHelper.copyWithCollection(functions, SysFunctionDTO.class));
                }
                return sysRoleDTO;
            }).collect(Collectors.toList());

//            PageResult<SysRoleDTO> result = new PageResult<>(ipage.getTotal(),ipage.getPages(),dtoList);
            return dtoList;
        }

       return null;
    }


    @Override
    public List<SysFunctionDTO> permissions() {

        LambdaQueryWrapper<SysFunction> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysFunction::getCompanyId,CurrentUserHolder.get().getCompanyId());
        List<SysFunction> sysFunctions = functionMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(sysFunctions)){
            return BeanHelper.copyWithCollection(sysFunctions,SysFunctionDTO.class);
        }
        return null;
    }


    @Override
    public List<SysCompanyUserDTO> subAdmin() {

        //查询管理员
        LambdaQueryWrapper<SysRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getCompanyId,CurrentUserHolder.get().getCompanyId());
        wrapper.likeRight(SysRole::getRoleName,NcConstant.ADMIN_ROLE_PREFIX);
        List<SysRole> sysRoles = roleMapper.selectList(wrapper);


        List<SysCompanyUserDTO> companyUserDTOS =new ArrayList<>();
        if (!CollectionUtils.isEmpty(sysRoles)){

            for (SysRole sysRole : sysRoles) {

                //查询角色员工关联表
                LambdaQueryWrapper<SysCompanyUserRole> roleWrappcer = new LambdaQueryWrapper<>();
                roleWrappcer.eq(SysCompanyUserRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
                roleWrappcer.eq(SysCompanyUserRole::getRoleId, sysRole.getId());
                List<SysCompanyUserRole> companyUserRoles = companyUserRoleMapper.selectList(roleWrappcer);

                //获取以员工id分组的角色
                Map<Long, List<SysCompanyUserRole>> map = companyUserRoles.stream().collect(Collectors.groupingBy(SysCompanyUserRole::getCompanyUserId));

                for (Long companyUserId : map.keySet()) {

                    SysCompanyUser sysCompanyUser = companyUserMapper.selectById(companyUserId);
                    SysCompanyUserDTO sysCompanyUserDTO = BeanHelper.copyProperties(sysCompanyUser, SysCompanyUserDTO.class);

                    if (sysCompanyUserDTO!=null){

                        List<SysCompanyUserRole> sysCompanyUserRoleList = map.get(companyUserId);
                        List<SysRole> roles = sysCompanyUserRoleList.stream().map(sysCompanyUserRole -> {

                            SysRole role = roleMapper.selectById(sysCompanyUserRole.getRoleId());
                            return role;
                        }).collect(Collectors.toList());

                        //设置员工的角色信息
                        sysCompanyUserDTO.setRoles(BeanHelper.copyWithCollection(roles,SysRoleDTO.class));
                        companyUserDTOS.add(sysCompanyUserDTO);
                    }

                }

            }

        }
        return companyUserDTOS;
    }

    @Override
    public void saveSubAdmin(Map<String, Object> map) {

        Integer userId = (Integer) map.get("userId");

        ArrayList<Integer> roleIds = (ArrayList) map.get("roleIds");


        if (userId==null && CollectionUtils.isEmpty(roleIds)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        for (Integer roleId : roleIds) {
            SysCompanyUserRole companyUserRole=new SysCompanyUserRole();
            companyUserRole.setCompanyId(CurrentUserHolder.get().getCompanyId());
            companyUserRole.setCompanyUserId(Long.valueOf(userId.toString()));
            companyUserRole.setRoleId(Long.valueOf(roleId.toString()));
            companyUserRoleMapper.insert(companyUserRole);

        }


        }

    @Override
    public void delSubAdmin(Long id) {
        if (id==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        LambdaQueryWrapper<SysCompanyUserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUserRole::getCompanyUserId,id);
        wrapper.eq(SysCompanyUserRole::getCompanyId,CurrentUserHolder.get().getCompanyId());
        companyUserRoleMapper.delete(wrapper);

    }

    /**
     * 获取当前用户员工信息
     * @return
     */
    @Override
    public SysCompanyUserDTO currentUser() {
        SysCompanyUser companyUser = companyUserMapper.selectById(CurrentUserHolder.get().getCompanyUserId());
        SysCompanyUserDTO companyUserDTO = BeanHelper.copyProperties(companyUser, SysCompanyUserDTO.class);
        return companyUserDTO;
    }

    //新增企业
    @Override
    public void insertCompany(SysCompanyRoleDTO companyRoleDTO) {
        if (companyRoleDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //判断企业是否存在
        LambdaQueryWrapper<SysCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompany::getName,companyRoleDTO.getName());
        Integer name = companyMapper.selectCount(wrapper);
        if (name>0){
            throw new NcException(ResponseEnum.COMPANY_FOUND);
        }

        //添加一个企业
        SysCompany sysCompany = new SysCompany();
        sysCompany.setName(companyRoleDTO.getName());//企业全称
        sysCompany.setIndustryId(companyRoleDTO.getIndustryId());//行业id
        sysCompany.setIndustryName(companyRoleDTO.getIndustryName());//行业名称
        sysCompany.setCompanyScale(companyRoleDTO.getCompanyScale());//人员规模
        sysCompany.setLocationCode(companyRoleDTO.getLocationId());//所在地区域编码
        sysCompany.setLocationName(companyRoleDTO.getLocationName());//行政区名称
        sysCompany.setAuditStatus((short)1);//

        LambdaQueryWrapper<SysCompanyUser> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysCompanyUser::getId,CurrentUserHolder.get().getCompanyUserId());
        SysCompanyUser userId = companyUserMapper.selectOne(wrapper1);//获取userId
        sysCompany.setUserId(userId.getUserId());
        sysCompany.setCreateTime(new Date());
        companyMapper.insert(sysCompany);

        //企业用户表同步一条创建者数据，设置默认权限
        SysCompanyUser companyUser = new SysCompanyUser();
        companyUser.setUserId(sysCompany.getUserId());
        companyUser.setCompanyId(sysCompany.getId());
        companyUser.setCompanyName(companyRoleDTO.getName());
        companyUser.setPost(companyRoleDTO.getPost());
        companyUser.setTimeEntry(new Date());
        companyUser.setEnable((short)1);
        companyUser.setCreateTime(new Date());
        companyUser.setUpdateTime(new Date());
        companyUser.setMobile(CurrentUserHolder.get().getMobile());
        companyUser.setUserName(CurrentUserHolder.get().getUsername());
        companyUserMapper.insert(companyUser);

        //默认企业创建者的角色
        SysRole sysRole1 = new SysRole();
        sysRole1.setRoleName("ROLE_ADMIN_CREATEOR");
        sysRole1.setRoleDesc("创建者");
        sysRole1.setCompanyId(sysCompany.getId());
        SysRole sysRole2 = new SysRole();
        sysRole2.setRoleName("ROLE_ADMIN_SYS");
        sysRole2.setRoleDesc("系统管理员");
        sysRole2.setCompanyId(sysCompany.getId());
        roleMapper.insert(sysRole1);
        roleMapper.insert(sysRole2);
        //同步到角色权限表
        SysCompanyUserRole sysCompanyUserRole1 = new SysCompanyUserRole();
        sysCompanyUserRole1.setCompanyUserId(companyUser.getId());
        sysCompanyUserRole1.setRoleId(sysRole1.getId());
        sysCompanyUserRole1.setCompanyId(sysCompany.getId());

        SysCompanyUserRole sysCompanyUserRole2 = new SysCompanyUserRole();
        sysCompanyUserRole2.setCompanyUserId(companyUser.getId());
        sysCompanyUserRole2.setRoleId(sysRole2.getId());
        sysCompanyUserRole2.setCompanyId(sysCompany.getId());

        companyUserRoleMapper.insert(sysCompanyUserRole1);
        companyUserRoleMapper.insert(sysCompanyUserRole2);
        //默认添加角色权限表
        //创建者权限
        SysRoleFunction sysRoleFunction1 = new SysRoleFunction();
        SysRoleFunction sysRoleFunction2 = new SysRoleFunction();
        for (long functionId = 1; functionId <= 22; functionId++) {
            if (functionId<=8){
                //创建者
                sysRoleFunction1.setRoleId(sysRole1.getId());
                sysRoleFunction1.setFunctionId(functionId);
                roleFunctionMapper.insert(sysRoleFunction1);
                //系统管理员
                sysRoleFunction2.setRoleId(sysRole2.getId());
                sysRoleFunction2.setFunctionId(functionId);
                roleFunctionMapper.insert(sysRoleFunction2);
            }
            //系统管理员
            sysRoleFunction2.setRoleId(sysRole2.getId());
            sysRoleFunction2.setFunctionId(functionId);
            roleFunctionMapper.insert(sysRoleFunction2);
        }
    }


    @Override
    public List<SysRoleDTO> querySysRole() {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
        List<SysRole> sysRoles = roleMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(sysRoles)) {
            List<SysRoleDTO> sysRoleDTOS = BeanHelper.copyWithCollection(sysRoles, SysRoleDTO.class);
            List<SysRoleDTO> collect = sysRoleDTOS.stream().map(sysRoleDTO -> {
                LambdaQueryWrapper<SysRoleFunction> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(SysRoleFunction::getRoleId, sysRoleDTO.getId());
                List<SysRoleFunction> sysRoleFunctions = roleFunctionMapper.selectList(wrapper1);
                List<Long> functionIds = sysRoleFunctions.stream().map(sysRoleFunction -> {
                    return sysRoleFunction.getFunctionId();
                }).collect(Collectors.toList());
                LambdaQueryWrapper<SysFunction> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.in(SysFunction::getId, functionIds);
                List<SysFunction> sysFunctionList = functionMapper.selectList(wrapper2);
                List<SysFunctionDTO> sysFunctionDTOS =
                        BeanHelper.copyWithCollection(sysFunctionList, SysFunctionDTO.class);
                sysRoleDTO.setSysFunctionAbbrList(sysFunctionDTOS);
                return sysRoleDTO;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public List<SysFunctionDTO> queryPermissions(List<SysRoleDTO> adminListData) {
        LambdaQueryWrapper<SysFunction> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysFunction::getCompanyId,CurrentUserHolder.get().getCompanyId());
        List<SysFunction> sysFunctionList = functionMapper.selectList(wrapper);
        return BeanHelper.copyWithCollection(sysFunctionList,SysFunctionDTO.class);
        /*List<List<SysFunctionDTO>> collect = sysRoleDTOS.stream().map(sysRoleDTO -> {
            for (SysRoleDTO roleDTO : list) {
                if (roleDTO.getId().equals(sysRoleDTO.getId())) {
                    return sysRoleDTO.getSysFunctionAbbrList();
                }
            }
            return null;
        }).collect(Collectors.toList());
        List<SysFunctionDTO> list1 =new ArrayList<>();
        for (List<SysFunctionDTO> sysFunctionDTOS : collect) {
            list1.addAll(sysFunctionDTOS);
        }
        return list1;*/
    }

    @Override
    public void updateSysRole(SysRoleFunctionDTO sysRoleFunctionDTO) {
        List<Long> functionIdList = sysRoleFunctionDTO.getFunctionIdList();
        List<Long> list=new ArrayList<>();
        List<Long> have=new ArrayList<>();
        LambdaQueryWrapper<SysFunction> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysFunction::getCompanyId,CurrentUserHolder.get().getCompanyId());
        Integer integer = functionMapper.selectCount(wrapper);
        for (int i = 1; i <= integer; i++) {
            list.add((long)i);
            for (Long aLong : functionIdList) {
                if ((aLong == (long) i)){
                    have.add((long)i);
                }
            }
        }
        Long roleId = sysRoleFunctionDTO.getRoleId();
        LambdaQueryWrapper<SysRoleFunction> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(SysRoleFunction::getRoleId,roleId);
        wrapper1.in(SysRoleFunction::getFunctionId,list);
        List<SysRoleFunction> sysRoleFunctions = roleFunctionMapper.selectList(wrapper1);
        if (!CollectionUtils.isEmpty(sysRoleFunctions)){
            roleFunctionMapper.delete(wrapper1);
        }
        if (!CollectionUtils.isEmpty(have)){
            for (Long aLong : have) {
                SysRoleFunction roleFunction=new SysRoleFunction();
                roleFunction.setFunctionId(aLong);
                roleFunction.setRoleId(roleId);
                roleFunctionMapper.insert(roleFunction);
            }
        }
    }
}

